import { asyncRoutes, constantRoutes } from '@/router'

/**
 * 以用户的权限和每一个路由的需要的权限作比较
 * @param roles
 * @param route
 * @return {Boolean}
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }  // 浅拷贝
    if (hasPermission(roles, tmp)) { 
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)  // 递归
      }
      res.push(tmp)  // 把符合权限的路由推入新数组并输出
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes) // 把最终路由数组保存到 vuex 中，渲染菜单时候用
  }
}

const actions = {
  // 根据权限配置路由
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {  // 如果用户有admin权限，默认全部显示
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)  // 筛选动态路由数组
      }
      commit('SET_ROUTES', accessedRoutes) 
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
